package com.training.controller;

import com.training.entity.Student;
import com.training.entity.User; // Import User entity
import com.training.entity.Teacher; // 新增导入 Teacher 实体
import com.training.service.StudentService;
import com.training.service.UserService; // Import UserService
import com.training.service.TeacherService; // 新增导入 TeacherService
import org.springframework.beans.factory.annotation.Autowired; // Import Autowired
import org.springframework.stereotype.Controller; // Import Controller
import org.springframework.ui.Model; // Import Model
import org.springframework.web.bind.annotation.GetMapping; // Import GetMapping
import org.springframework.web.bind.annotation.PostMapping; // Import PostMapping
import org.springframework.web.bind.annotation.RequestParam; // Import RequestParam
import org.springframework.web.servlet.mvc.support.RedirectAttributes; // Import RedirectAttributes

import javax.servlet.http.HttpSession; // Import HttpSession
import org.slf4j.Logger; // 导入 Logger
import org.slf4j.LoggerFactory; // 导入 LoggerFactory

@Controller // Mark this as a Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class); // 初始化 Logger

    @Autowired // Auto-inject UserService instance
    private UserService userService;
    @Autowired
    private StudentService studentService;
    @Autowired // 新增注入 TeacherService
    private TeacherService teacherService;

    /**
     * Display the login page.
     * @param model Model object
     * @return Template name for the login page
     */
    @GetMapping("/login") // Respond to GET requests for /login
    public String showLoginPage(Model model) {
        return "login"; // Return templates/login.html
    }

    /**
     * Handle login form submission.
     * Corresponds to requirement FR-JSDL-1 (Teacher Login) and FR-XSDL-1 (Student Login).
     * @param username Username entered by the user
     * @param password Password entered by the user
     * @param session HttpSession object to store logged-in user information
     * @param redirectAttributes Used to pass messages after redirection
     * @return Redirect to different pages based on login success and user role
     */
    @PostMapping("/login") // Respond to POST requests for /login
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes redirectAttributes) {
        // Basic validation: username and password cannot be empty (as per constraints)
        if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
            redirectAttributes.addFlashAttribute("error", "用户名和密码不能为空。");
            logger.warn("登录尝试失败: 用户名或密码为空.");
            return "redirect:/login"; // Redirect back to login page with error
        }

        // Authenticate user
        User user = userService.authenticateUser(username, password);

        System.out.println("LoginController - Authenticated user object after authentication: " + user);
        logger.info("尝试登录用户: {}", username);

        if (user != null) {
            // 存储完整的User对象，以便前端可以访问其属性（例如用户名）
            session.setAttribute("loggedInUser", user);
            // 存储用户的ID，以便其他控制器可以进行权限或数据检索
            session.setAttribute("loggedInUserId", user.getId());

            redirectAttributes.addFlashAttribute("successMessage", "登录成功！");

            String userRole = user.getRole();
            logger.info("用户 {} 登录成功，角色为：{}", username, userRole);

            // Redirect based on user role
            if ("TEACHER".equalsIgnoreCase(userRole)) {
                // 如果是教师，获取教师详细信息并存入session
                Teacher teacher = teacherService.getTeacherByUserId(user.getId());
                if (teacher != null) {
                    session.setAttribute("teacher", teacher); // 将 Teacher 对象存入 Session
                    logger.info("教师 {} (用户ID: {}) 对应的教师实体信息已载入。", user.getUsername(), user.getId());
                } else {
                    logger.warn("教师 {} (用户ID: {}) 登录成功，但未找到对应的教师实体信息。", user.getUsername(), user.getId());
                    // 可以选择给用户一个提示或处理未找到教师信息的情况
                }
                return "redirect:/teacher/dashboard"; // *** 修改后的重定向路径 ***
            } else if ("STUDENT".equalsIgnoreCase(userRole)) {
                // 如果User对象的ID就是studentId，则直接使用user.getId()
                // 否则，如果你的User对象内部有getStudentId()方法，应使用它
                Student student = studentService.getStudentByUserId( user.getId());
                if (student != null) {
                    session.setAttribute("loggedInStudentId", student.getId()); // 保持此行，确保学生ID也存在
                    session.setAttribute("student", student); // 也可以将 Student 对象存入 Session
                    logger.info("学生 {} (用户ID: {}) 对应的学生实体信息已载入。", user.getUsername(), user.getId());
                } else {
                    logger.warn("学生 {} (用户ID: {}) 登录成功，但未找到对应的学生实体信息。", user.getUsername(), user.getId());
                }

                return "redirect:/student/dashboard"; // Redirect students to student dashboard
            } else {
                // Handle other roles or default redirect
                redirectAttributes.addFlashAttribute("error", "用户角色未知或配置不正确。");
                logger.warn("用户 {} 登录成功，但角色未知或配置不正确: {}", username, userRole);
                return "redirect:/login"; // Default to login page with error
            }
        } else {
            // Login failed
            redirectAttributes.addFlashAttribute("error", "用户名或密码不正确。");
            logger.warn("用户 {} 登录失败：用户名或密码不正确。", username);
            return "redirect:/login"; // Redirect back to login page with error
        }
    }

    /**
     * Handle logout request.
     * @param session HttpSession object to invalidate
     * @param redirectAttributes Used to pass messages after redirection
     * @return Redirect to the login page after logout
     */
    @GetMapping("/logout") // Respond to GET requests for /logout
    public String logout(HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser != null) {
            logger.info("用户 {} 登出。", loggedInUser.getUsername());
        }
        session.invalidate(); // Invalidate the session
        redirectAttributes.addFlashAttribute("logout_success", "您已成功退出。");
        return "redirect:/login"; // Redirect to login page
    }
}